package com.atguigu.eduOrder.controller;


import com.atguigu.common.Result;
import com.atguigu.eduOrder.entity.Order;
import com.atguigu.eduOrder.service.OrderService;
import com.atguigu.serviceBase.exception.GuliException;
import com.atguigu.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author smday
 * @since 2020-08-01
 */
@RestController
@RequestMapping("/eduOrder/order")

public class OrderController {

    @Resource
    private OrderService orderService;

    @ApiOperation("生成订单")
    @PostMapping("/createOrder/{courseId}")
    public Result createOrder(@PathVariable String courseId, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            throw new GuliException("暂未登录");
        }
        //创建订单号,生成orderNo todo 需要判断订单是否存在
        String orderNo = orderService.createOrder(courseId, memberId);
        return Result.ok().data("orderNo", orderNo);
    }


    @ApiOperation("根据订单No查询订单信息")
    @GetMapping("/{orderNo}")
    public Result getOrderInfo(@PathVariable String orderNo) {

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);

        Order order = orderService.getOne(wrapper);
        return Result.ok().data("order", order);

    }

    //根据课程id和用户id查询订单表中订单状态
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);//支付状态 1代表已经支付
        int count = orderService.count(wrapper);
        if(count>0) { //已经支付
            return true;
        } else {
            return false;
        }
    }
}

